<?php

namespace App\Http\Controllers\Cruise\Web;

use App\Http\Controllers\BaseController;
use App\Http\Validate\Cruise\CruiseProjectValidate;
use App\Library\Rms\RmsShopApi;
use App\Models\Cruise\CruiseProjectCategoryModel;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Service\Cruise\CruiseProject\CruiseCategoryService;
use App\Service\Cruise\CruiseProject\CruiseProjectParam;
use App\Service\Cruise\CruiseProject\CruiseProjectService;
use App\Service\OpenShop\User\RmsUserService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class ShopController extends BaseController
{
    public function lists(Request $request): JsonResponse
    {
        $provinceCode  = (string)$request->get('provinceCode');
        $cityCode      = (string)$request->get('cityCode');
        $regionCode    = (string)$request->get('regionCode');
        $shopStatus    = $request->get('shopStatus'); // 0开业 1关闭 2筹备中
        $grade         = (int)$request->get('grade'); // 1ST ..
        $bookRateStart = (float)$request->get('bookRateStart'); // 1=1%
        $bookRateEnd   = (float)$request->get('bookRateEnd'); // 1=1%
        $notCheckDay   = (int)$request->get('notCheckDay'); // 未巡检天数
        $pageSize      = (int)$request->get('pageSize', 20);
        $pageNum       = (int)$request->get('pageNum', 1);
        $shopIds       = (string)$request->get('shopIds', '');
        $shopIds       = $shopIds ? explode(',', $shopIds) : []; // TODO
        $supervisorUid = (int)$request->get('supervisorUid'); //督导

        if ($notCheckDay) {
            $lastCruiseTime = time() - 86400 * $notCheckDay;
        } else {
            $lastCruiseTime = 0;
        }

        // todo 督导负责门店兼容查询
        if ($supervisorUid > 0) {
            $supervisorShopIds = OpenShopOrderManagerModel::query()
                                                          ->where("managerUid", $supervisorUid)
                                                          ->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_5)
                                                          ->pluck("shopId")
                                                          ->toArray();

            if ($shopIds) {
                // todo 督导和门店同时传值  此时取交集
                $shopIds = array_intersect($shopIds, $supervisorShopIds);
            } else {
                // todo 门店未传值  此时督导负责门店覆盖门店参数
                $shopIds = $supervisorShopIds;
            }

            $shopIds = (empty($shopIds) ? [-1] : $shopIds);
        }

        $data = (new RmsShopApi())->cruiseShopFilter(
            $provinceCode,
            $cityCode,
            $regionCode,
            $shopStatus,
            $grade,
            $bookRateStart,
            $bookRateEnd,
            $lastCruiseTime,
            $shopIds,
            $pageSize,
            $pageNum
        );

        if ($data['code']) {
            $shopCodes = array_column($data['data']['list'], 'shopCode');
            $merchantUserIds = OpenShopSignOrderModel::query()->whereIn('shopCode', $shopCodes)->select('shopCode', 'merchantUserId')->get()->keyBy('shopCode');
            $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds($merchantUserIds->pluck('merchantUserId')->toArray())['data'])->keyBy('id');

            $data['data']['list'] = collect($data['data']['list'])
                ->map(function ($item) use ($merchantUserIds, $userInfos) {
                    $merchantUserId = $merchantUserIds[$item['shopCode']]['merchantUserId'] ?? 0;
                    $merchantName = $userInfos[$merchantUserId]['username'] ?? '';

                    return [
                        'shopId'            => $item['id'],
                        'shopCode'          => $item['shopCode'],
                        'shopName'          => $item['name'],
                        'grade'             => $grade = $item['grade'],
                        'gradeText'         => OpenShopSiteLocationModel::HOUSE_GRADE_SIFT_MAPPING[$grade] ?? '',
                        'shopType'          => $item['type'],
                        'shopTypeText'      => RmsShopApi::SHOP_TYPE_MAPPING[$item['type']] ?? '',
                        'merchantName'      => $merchantName,
                        'region'            => $item['addressPrefix'],
                        'startBusinessDate' => $item['formalUseAt'] ? date('Y-m-d', $item['formalUseAt']) : '-',
                        'bookRate'          => ($item['orderRatio']) . '%',
                        'lastCheckDay'      => $item['lastCruiseTime'] == 0 ? '' : date('Y-m-d',
                            $item['lastCruiseTime']), // 未巡检返回空字符
                        'notCheckDay'       => $item['lastCruiseTime'] == 0 ? '-' : ceil((time() - $item['lastCruiseTime']) / 86400),
                        'shopStatus'        => $item['status'],
                        'shopStatusText'    => RmsShopApi::SHOP_STATUS_TEXT[$item['status']] ?? '',
                    ];
                })->toArray();

            return $this->success($data['data']);
        }

        return $this->fail(1, $dta['msg'] ?? '系统异常', $data['data'] ?? []);
    }
}
